<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/7/23
 * Time: 23:15
 */
namespace App\Http\Controllers\Admin\Area;

use App\Http\Controllers\AdminController;
use App\Http\Requests\StoreAreaRequest;
use App\Http\Requests\StoreSetareaRequest;
use Illuminate\Support\Facades\DB;
class AreaController extends AdminController
{

    //定义允许的文件上传类型
    public $passUpFileType = array('image/jpg','image/png','image/jpeg','image/gif');
    //定义上传文件路径
    public $uploadPath = 'upload/menuList/';
    //定义banner_img上传路径
    public $bannerUploadPath = 'upload/menuList/banner/';
    //定义新的上传文件名
    public $newFileNamw = '';
    //定义banner_img新的上传文件名
    public $bannerNewFileNamw = '';

    /**
     * 网站栏目管理列表页面
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <Y-m-d H:i:s>
     * @param   <null>
     * @des     <描述:获取网站栏目管理列表数据与搜索数据>
     * @return  <view>
     */
    public function index()
    {
        $data = array();
        $data = $this->getList('index',$data);
        return \Helpers::showViewCURD('Admin.Area.index',3,'',$data);
    }

    /**
     * 网站栏目管理新增页面
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-7-28 19:51>
     * @param   <null>
     * @des     <描述:显示新增栏目管理表单>
     * @return  <view>
     */
    public function create()
    {
        $data = array();
        $data = $this->getCreateOrEditD($data,'arr');
        return \Helpers::showViewCURD('Admin.Area.create',1,'新增',$data);
    }

    /**
     * 新增操作
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-8-2 23:35>
     * @des     <描述:新增操作>
     * @param   <StoreMenuMgmtRequest>  <$request>  [验证过后的数据对象]
     * @return  <404||新增成功||新增失败>
     */
    public function store(StoreAreaRequest $request)
    {
        //验证post提交
        if($request->isMethod('post'))
        {
            //入库数据处理
            $inserArr = $this->addOrEditFormatD($request);
            //入库
            $res = DB::table('area')->insertGetId($inserArr);
            //根据入库结果返回状态
            $errors = $res ? '新增成功!' : '新增失败!';
            $isSuccess = $res ? 'success' : 'error';
            \Helpers::insertUserActionLog('area', 'add', $res, $isSuccess, $inserArr);
            return redirect()->back()->withErrors($errors);
            
        }else{
            abort(404);
        }
    }

    /**
     * 网站列表修改页面...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-29 10:10>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站列表修改页面>
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        //验证数据
        if(empty($id)) abort(404);
        $data = array();
        $data = $this->getCreateOrEditD($data,'arr');
        $data['editList'] = DB::table('area')->where('id',$id)->first();
        return \Helpers::showViewCURD('Admin.Area.create',2,'修改',$data);
    }

    /**
     * 网站列表修改操作...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-29 10:10>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站列表修改操作>
     * @param $id
     * @param StoreMenuMgmtRequest $request
     * @return $this
     */
    public function update($id,StoreAreaRequest $request)
    {
        if(empty($id)) abort(404);
        //修改数据处理
        $editArr = $this->addOrEditFormatD($request,'edit');
        $res = DB::table('area')
        ->where('id',intval($id))
        ->update($editArr);
        //根据入库结果返回状态
        $errors = $res ? '修改成功!' : '修改失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('area','up',$id,$isSuccess,$editArr);

        return redirect()->back()->withErrors($errors);
    }

    /**
     * 网站列表删除操作...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-29 10:10>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站列表删除操作>
     * @param $id
     * @return mixed
     */
    public function del($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac'])) abort(404);
        $status = $_POST['ac'];
        //检测当前数据是否存在下级,有下级必须删除下级后才能删除上级
        $hasChildren = DB::table('area')->where('status',$status)->where('pid',$id)->first();
        if($hasChildren) die(json_encode(array('error'=>-1,'msg'=>'当前数据存在子集分类,请删除后再试!')));
        //status:1.逻辑删除数据,2.物理删除数据
        if($status == 1) $res = DB::table('area')->where('id',intval($id))->update(array('status'=>2));
        if($status == 2) $res = DB::table('area')->where('id',intval($id))->delete();
        $preMsg = '删除';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('area','del',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 网站栏目管理回收站还原操作...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-29 10:10>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站栏目管理回收站还原操作>
     * @param $id
     * @return mixed
     */
    public function back($id)
    {
        //验证传参,ac 1.逻辑删除 2.物理删除 3.还原
        if(empty($id) || empty($_POST['ac'])) abort(404);
        //还原逻辑删除数据
        $res = DB::table('area')->where('id',intval($id))->update(array('status'=>1));
        $preMsg = '还原';
        $errorCode = $res ? 1 : -1;
        $msg = $res ? $preMsg.'成功!' : $preMsg.'失败!';
        $isSuccess = $res ? 'success' : 'error';
        \Helpers::insertUserActionLog('area','back',$id,$isSuccess,$_POST);
        return json_encode(array('error'=>$errorCode,'msg'=>$msg));
    }

    /**
     * 网站栏目管理回收站...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-10-29 10:10>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站栏目管理回收站>
     * @return mixed
     */
    public function rb()
    {
        $data = array();
        $data = $this->getList('rb',$data);
        return \Helpers::showViewCURD('Admin.Area.index',4,'',$data);
    }

    /**
     * 新增或修改操作公共处理数据...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-8-2 23:35>
     * @des     <描述:新增或修改操作公共处理数据>
     * @param   <obj>       <$request>      [处理数据源]
     * @param   <string>    <$addOrEdit>    [add||edit新增或修改操作参数变更]
     * @return  <array>     <$postData>
     */
    public function addOrEditFormatD($request,$addOrEdit='add')
    {
        $postData = $request->all();
        //释放不必要的_token参数
        unset($postData['_token']);
        $pid = explode('_',$postData['pid']);
        $postData['pid'] = !empty($pid[0]) ? $pid[0] : 0;
        $postData['path'] = !empty($pid[0]) && $pid[1] != '' ? $pid[1].','.$pid[0] : 0;
        $addOrEditTimeK = $addOrEdit == 'edit' ? 'update_time' : 'create_time';
        if($addOrEdit == 'edit') unset($postData['_method']);
        $postData[$addOrEditTimeK] = time();
        $postData['status'] = 1;
        $userInfo = json_decode(session('Z_AdminiUser'),true);
        $postData['create_uid'] = $userInfo['id'];
        unset($postData['_method']);
        return $postData;
    }

    /**
     * 新增或修改页面表单数据公共查询...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-8-2 23:35>
     * @des     <描述:新增或修改页面表单数据公共查询...>
     * @param   <array>     <$data>         [返回数据源]
     * @param   <string>    <$strOrArr>     [下拉生成数据为下拉字符串或者数组]
     * @return  <array>     <$data>         [返回数据数组]
     */
    public function getCreateOrEditD($data,$strOrArr='str')
    {
        //获取所属父级别字典
        $where = array('status'=>array('sb'=>'=','v'=>1));
        $pidListRes =\Helpers::DbForTree('area','','id,pid,path,name,concat(path,\',\',id) as bpath',$where,'bpath');
        //生成所属父级栏目下拉字符串
        $data['pidListStr'] = \Helpers::createTreeSelect($pidListRes,$strOrArr,array('id'=>'id','pid'=>'pid','path'=>'path','title'=>'name'));
        // //基于上一个where数组再新增查询参数
        // $where['identify'] = array('sb'=>'=','v'=>'menu_show_modules_identify');
        // $where['pid'] = array('sb'=>'<>','v'=>0);
        // //获取网站栏目管理数据
        // $data['dataddshowmodels'] = \Helpers::DbForTree('datadd',array('type','title'),'',$where);
        return $data;
    }

    /**
     * 网站栏目管理获取首页列表数据方法...
     * @author  <ZhengYaFeng>
     * @access  <public>
     * @date    <2016-8-2 23:35>
     * @param   <null>
     * @return  <mixed>
     * @des     <描述:网站栏目管理获取首页列表数据方法>
     * @param string $flag
     * @param $data
     * @return mixed
     */
    public function getList($flag='index',$data)
    {

        $selectId = $flag == 'rb' ? 2 : 1;
        //获取所属父级别字典
        $res = DB::select('
                    select wj_area.*,concat(wj_area.path,\',\',wj_area.id) as bpath,wj_adminuser.username
                    from wj_area
                    left join wj_adminuser
                    on wj_adminuser.id = wj_area.create_uid
                    where wj_area.status = '.$selectId.'
                    order by bpath
                ');
        //生成公共处理前格式
        $data['list'] = empty($res) ? '' : json_encode($res);
        //公共处理数据给页面
        $data['list'] = json_decode($data['list'],true);
        return $data;
    }
    
    public function setarea(StoreSetareaRequest $request)
    {
        if($request->isMethod('PUT')) {
            $post = $request->all();
            $upArr = [];
            if(!empty($post['group_servant_id']))
            {
                $areaJson = json_encode($post['group_servant_id']);
                $upArr = ['area_json'=>$areaJson];
                $res = DB::table('admini_systeminfo')->update($upArr);                
            }else{
                $upArr = ['area_json'=>''];
                $res = DB::table('admini_systeminfo')->update($upArr);
            }

            $errors = $res ? '设置成功!' : '设置失败!';
            $isSuccess = $res ? 'success' : 'error';
            \Helpers::insertUserActionLog('setarea','set',$res,$isSuccess,$upArr);
            return redirect()->back()->withErrors($errors);
        }else{
           
        
            $data = [];
            $data['list'] = DB::table('area')
                        ->select('id','name')
                        ->where('status',1)
                        ->where('level',2)
                        ->get();
            $data['select'] = DB::table('admini_systeminfo')
                                ->select('area_json')
                                ->first();
                                
            $data['select'] = !empty($data['select']->area_json) ? json_decode($data['select']->area_json,true): '';
            return \Helpers::showViewCURD('Admin.Area.setarea',1,'设置',$data);
        }
    }

}